/*
 * @Author: mylesshie@gmail.com
 * @Date: 2020-07-03 17:33:57
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-07-03 22:44:13
 * @description:
 */

import React, { useState, useEffect } from 'react'
import { View, Text, Modal, TouchableOpacity } from 'react-native'
import { Input } from 'react-native-elements'
import styles from './styles'

const TextPop = props => {
  const [inputValue, setInputValue] = useState(props.defaultValue)

  useEffect(() => {
    setInputValue(props.defaultValue)
  }, [props.visible])

  const defaultOptions = {
    onShow: () => {},
    onRequestClose: () => {},
    onDismiss: () => {},
    transparent: true,
    animationType: 'fade',
    hardwareAccelerated: false,
    presentationStyle: 'overFullScreen',
    title: '提示',
    cancelText: '取消',
    submitText: '确定',
    placeholder: '请输入内容',
    maxLength: 100,
    onCancel: () => {},
    onSubmit: () => {}
  }

  const opts = Object.assign({}, defaultOptions, props)

  const _onSubmit = () => {
    opts.onSubmit && opts.onSubmit(inputValue)
    setInputValue('')
  }

  const _onCancel = () => {
    opts.onCancel && opts.onCancel()
    setInputValue('')
  }

  const _onChangeText = (value) => {
    setInputValue(value)
  }

  const innerComponent = <View>
    <Input placeholder={opts.placeholder} maxLength={opts.maxLength} value={inputValue} onChangeText={text => _onChangeText(text)} />
  </View>

  return (
    <Modal
      visible={props.visible}
      onShow={opts.onShow}
      onDismiss={opts.onDismiss}
      onRequestClose={opts.onRequestClose}
      transparent={opts.transparent}
      animationType={opts.animationType}
      hardwareAccelerated={opts.hardwareAccelerated}
      presentationStyle={opts.presentationStyle}
    >
      <View style={styles.wrap}>
        <View style={styles.container}>
          <View style={styles.popHeader}>
            <Text style={styles.popTitle}>{opts.title}</Text>
          </View>
          <View style={styles.popBody}>{opts.bodyCompontent || innerComponent}</View>
          <View style={styles.popFooter}>
            {opts.onCancel ? (
              <TouchableOpacity style={styles.btnWrap} onPress={_onCancel}>
                <View style={[styles.popBtn, styles.leftBtn]}>
                  <Text style={[styles.popBtnText, styles.leftBtnText]}>{opts.cancelText}</Text>
                </View>
              </TouchableOpacity>
            ) : null}
            <TouchableOpacity style={styles.btnWrap} onPress={_onSubmit}>
              <View style={styles.popBtn}>
                <Text style={[styles.popBtnText, styles.rightBtnText]}>{opts.submitText}</Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </Modal>
  )
}

export default TextPop
